const express = require('express')
const app = express()
const path = require('path')

//启动处理body的中间健
// app.use(express.json())
// app.use(express.urlencoded())

//手写处理body请求的中间件
/*app.use((req, res, next) => {
  // console.log(req);
  let dataStr = ""
  req.on("data", (chunk) => {
    // console.log(chunk.toString());//user=laoli&pass=123
    dataStr += chunk.toString()
  })
  req.on("end", () => {
    console.log("ok", dataStr);
    // dataStr.split("&")//["name=laoli","age=123"]
    //写法1
    // const o = {};
    // dataStr.split("&").forEach(item => {
    //   const [key, value] = item.split("=") //["name","laoli"]
    //   o[key] = value;
    // })
    // console.log(o, "oooooo");

    //写法2
    const data = dataStr.split("&").reduce((prev, current) => {
      const [key, value] = current.split("=");
      prev[key] = value;
      return prev;
    }, {})

    console.log(data, "data");

    //再中间件中，得到请求体body的值并处理为一个对象 添加给req的body属性上
    req.body = data;
    console.log('req.body',req.body)
    next()

  })


  // req.body = 123;
  // next()
})*/


app.post('/postData',(req,res)=>{

  const {
    name,
    sex,
    age
  }=req.body
  // console.log(req.body)
  if (!name||!sex||!age){
    return res.send({
      code:10001,
      msg:'提交数据失败',
      data:null
    })
  }

  res.send({
    code:10000,
    msg:'提交数据成功',
    data:{
      name,
      sex,
      age
    }
  })
})

app.get('/user',(req,res)=>{

  const {
    userId
  } = req.query

  if (userId !== '001'){
    return res.send({
      code:10001,
      message:'查询数据失败',
      data:null
    })
  }

  res.send({
    code:10000,
    message:'查询数据成功',
    data:{
      userId:'001',
      userName:'万登豪',
      userSex:'男',
      userAge:18
    }
  })

})

app.get('/userInfo/:userId',(req,res)=>{

  const {
    userId
  } = req.params

  if (userId !== '001'){
    return res.send({
      code:10001,
      message:'查询数据失败',
      data:null
    })
  }

  res.send({
    code:10000,
    message:'查询数据成功',
    data:{
      userId:'001',
      userName:'万登豪',
      userSex:'男',
      userAge:18
    }
  })

})


app.get('/1',(req,res)=>{

  const filePath = path.resolve(__dirname,'./基础的get请求.html')
  res.sendFile(filePath)

})
app.get('/2',(req,res)=>{

  const filePath = path.resolve(__dirname,'./getAjaxPath.html')
  res.sendFile(filePath)

})
app.get('/3',(req,res)=>{

  const filePath = path.resolve(__dirname,'./post请求.html')
  res.sendFile(filePath)

})

app.listen(8090,()=>{
  console.log('running!!! 可以访问 http://127.0.0.1:8090')
})